package core;

import fileoperation.FileStatus;
import gitobject.GitObject;
import repository.Repository;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class JitCatFile {
    final static String OBJECTS_PATH = Repository.getGitDir()+File.separator+"objects";
    /**
     * 根据传入type，返回文件的类型、内容或大小
     * @param hash
     * @param type
     * @throws UnsupportedEncodingException
     */
    public static void cat(String hash,String type) throws UnsupportedEncodingException {
        List<File> gitObjectsList = FileStatus.objectsList(OBJECTS_PATH);
        for(File gitObject : gitObjectsList){
            String id =  gitObject.toString().replace(OBJECTS_PATH,"").replace(File.separator,"");
            if(id.startsWith(hash)){
                GitObject gitObj = GitObject.deserialize(id);
                if(type.equals("type")) System.out.println(gitObj.getFmt());
                if(type.equals("content")) System.out.println(gitObj.getValue());
                if(type.equals("length")) System.out.println(gitObj.getValue().getBytes("UTF-8").length);
                return;
            }
        }
        System.out.printf("fatal: Not a valid object name %s\n", hash);
    }
}
